const query = require('../../dbConfig/index')

const get = async (ctx,next)=>{
	const body = ctx.request.body
	const offset = (body.pageNumber - 1) * Number(body.pageSize);  
	let sql = 'SELECT * FROM evaluate_paper';  
	let params = [];  
	  sql += ' LIMIT ? OFFSET ?';  
	  params.push(Number(body.pageSize));  
	  params.push(offset);
	const res = await query(sql,params)
	const total = await query(`SELECT COUNT(*) as total FROM evaluate_paper`)
	if(res.length>0){
		ctx.body={code:200,data:{records:res,total:total[0].total},msg:'成功'}
		next()
	}else{
		ctx.body={code:0,data:null,msg:'暂无数据'}
	}
}
const updata = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`UPDATE evaluate_paper SET is_open = ? WHERE id='${body.id}'`,[body.is_open])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
const add = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`INSERT INTO evaluate_paper (id,paper_name,is_open,evaluate_judges,createtime,remarks) VALUES (?,?,?,?,?,?)`,[body.id,body.paper_name,0,body.evaluate_judges,body.createtime,body.remarks])
	for(let i=0;i<body.evaluata_content.length;i++){
		let teacher_ids = body.evaluata_content[i].teacherId
		for(let j=0;j<body.evaluata_content[i].content.length;j++){
			const item = body.evaluata_content[i].content[j]
			await query(`INSERT INTO evaluate (evaluate_title,evaluate_tips,evaluate_posen,teacher_ids,evaluate_paper_id) VALUES (?,?,?,?,?)`,[item.content_title,item.content_tips,item.content_type,teacher_ids.join(','),body.id])
		}
	}
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
const remove = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`DELETE FROM evaluate_paper WHERE id='${body.id}'`)
	await query(`DELETE FROM evaluate WHERE evaluate_paper_id=${body.id}`)
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
const getEvaluateTitle = async (ctx,next)=>{
	console.log(ctx.request.body)
	const body = ctx.request.body
	if(body.id){
		let sql = `SELECT * FROM evaluate where evaluate_paper_id='${body.id}'`;
		const res = await query(sql)
		if(res.length>0){
			let teacher = []
			for(let i=0;i<res.length;i++){
				teacher.push(...res[i].teacher_ids.split(','))
				delete res[i].teacher_ids
			}
			const teachers = await query(`SELECT *
			FROM teacher
			WHERE teacher_id IN (${[...new Set(teacher)].join(',')})`)
			ctx.body={code:200,data:{teacher:teachers,evaluate_title:res},msg:'成功'}
			next()
		}else{
			ctx.body={code:0,data:null,msg:'评价问卷暂无数据'}
		}
	}
}
const getScore = async (ctx,next)=>{
	console.log(ctx.request.body)
	const body = ctx.request.body
	if(body.teacher_id){// 如果有 查询相关试题
		//TODO
	}
}
module.exports = {
	get,getScore,getEvaluateTitle,
	add,updata,remove
}